<template>
  <div class="modal-overlay" @click.self="handleClose">
    <div class="modal-container">
      <div class="modal-header">
        <h2>发布讨论</h2>
        <button class="close-btn" @click="handleClose">
          <svg viewBox="0 0 24 24" width="24" height="24" fill="currentColor">
            <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>
          </svg>
        </button>
      </div>

      <div class="modal-body">
        <div class="form-group">
          <label class="form-label">标题 <span class="required">*</span></label>
          <input 
            v-model="formData.title"
            type="text" 
            class="form-input"
            placeholder="请输入讨论标题"
            maxlength="100"
          />
          <div class="char-count">{{ formData.title.length }}/100</div>
        </div>

        <div class="form-group">
          <label class="form-label">内容 <span class="required">*</span></label>
          <div class="editor-wrapper">
            <div class="editor-toolbar">
              <button type="button" class="toolbar-btn" @click="showMathEditor = true" title="插入数学公式">
                <svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor">
                  <path d="M4 7h2v2h2v2H6v2H4v-2H2V9h2V7zm6-2h12v2H10V5zm0 4h12v2H10V9zm0 4h12v2H10v-2zm-4 4h2v2h2v2H6v-2H4v-2H2v-2h2v2z"/>
                </svg>
                公式
              </button>
              <button 
                type="button" 
                class="toolbar-btn" 
                @click="triggerImageUpload" 
                :disabled="uploading"
                title="插入图片"
              >
                <svg v-if="!uploading" viewBox="0 0 24 24" width="18" height="18" fill="currentColor">
                  <path d="M21 19V5c0-1.1-.9-2-2-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2zM8.5 13.5l2.5 3.01L14.5 12l4.5 6H5l3.5-4.5z"/>
                </svg>
                <svg v-else viewBox="0 0 24 24" width="18" height="18" fill="currentColor" class="spinning">
                  <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>
                </svg>
                {{ uploading ? '上传中...' : '图片' }}
              </button>
              <input 
                ref="imageInput"
                type="file"
                accept="image/*"
                multiple
                style="display: none"
                @change="handleImageUpload"
              />
            </div>
            <textarea 
              ref="contentTextarea"
              v-model="formData.content"
              class="form-textarea"
              placeholder="详细描述你的问题或想法..."
              rows="8"
            ></textarea>
            <div class="editor-footer">
              <div class="footer-left">
                <div class="image-previews" v-if="uploadedImages.length > 0">
                  <span class="images-label">已添加 {{ uploadedImages.length }} 张图片：</span>
                  <div class="image-list">
                    <div 
                      v-for="(img, index) in uploadedImages" 
                      :key="index"
                      class="image-preview-item"
                      :title="img.name"
                    >
                      <img :src="img.url" :alt="img.name" />
                      <button type="button" class="remove-image" @click="removeImage(index)" title="删除图片">
                        <svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor">
                          <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>
                        </svg>
                      </button>
                    </div>
                  </div>
                </div>
              </div>
              <div class="char-count">{{ formData.content.length }}字 {{ uploadedImages.length > 0 ? `· ${uploadedImages.length}图` : '' }}</div>
            </div>
          </div>
        </div>

        <div class="form-group">
          <label class="form-label">标签</label>
          <div class="tags-input">
            <span 
              v-for="(tag, index) in formData.tags" 
              :key="index"
              class="tag-item"
            >
              {{ tag }}
              <button class="tag-remove" @click="removeTag(index)">×</button>
            </span>
            <input 
              v-if="formData.tags.length < 5"
              v-model="tagInput"
              type="text" 
              class="tag-input"
              placeholder="添加标签（最多5个）"
              @keyup.enter="addTag"
              @blur="addTag"
            />
          </div>
          <div class="tag-suggestions">
            <span 
              v-for="tag in suggestedTags" 
              :key="tag"
              class="suggested-tag"
              @click="addSuggestedTag(tag)"
            >
              + {{ tag }}
            </span>
          </div>
        </div>
      </div>

      <div class="modal-footer">
        <button class="btn btn-cancel" @click="handleClose">取消</button>
        <button 
          class="btn btn-submit" 
          :disabled="!canSubmit || submitting"
          @click="handleSubmit"
        >
          {{ submitting ? '发布中...' : '发布' }}
        </button>
      </div>
    </div>
    
    <!-- 数学公式编辑器 -->
    <MathEditor 
      v-if="showMathEditor"
      @close="showMathEditor = false"
      @insert="handleInsertFormula"
    />
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { createDiscussion } from '../api/discussion'
import { uploadImage } from '../api/user'
import MathEditor from './MathEditor.vue'
import { toast } from '../utils/toast'

const emit = defineEmits(['close', 'submit'])

const formData = ref({
  title: '',
  content: '',
  tags: []
})

const tagInput = ref('')
const submitting = ref(false)
const showMathEditor = ref(false)
const contentTextarea = ref(null)
const imageInput = ref(null)
const uploadedImages = ref([])
const uploading = ref(false)

const suggestedTags = ref([
  '极限', '三角函数', '中级', '代数', '几何', '微积分', '概率统计'
])

const canSubmit = computed(() => {
  return formData.value.title.trim().length > 0 && 
         formData.value.content.trim().length > 0
})

function addTag() {
  const tag = tagInput.value.trim()
  if (tag && !formData.value.tags.includes(tag) && formData.value.tags.length < 5) {
    formData.value.tags.push(tag)
    tagInput.value = ''
  } else {
    tagInput.value = ''
  }
}

function addSuggestedTag(tag) {
  if (!formData.value.tags.includes(tag) && formData.value.tags.length < 5) {
    formData.value.tags.push(tag)
  }
}

function removeTag(index) {
  formData.value.tags.splice(index, 1)
}

async function handleSubmit() {
  if (!canSubmit.value || submitting.value) return
  
  submitting.value = true
  try {
    // 合并文字内容和图片
    let finalContent = formData.value.content
    
    // 如果有图片，将图片HTML添加到内容末尾
    if (uploadedImages.value.length > 0) {
      finalContent += '\n\n'
      uploadedImages.value.forEach(img => {
        // 使用img标签而不是markdown，更利于渲染
        finalContent += `<img src="${img.url}" alt="${img.name}" class="discussion-image" />\n`
      })
    }
    
    const submitData = {
      ...formData.value,
      content: finalContent
    }
    
    console.log('提交的内容:', submitData.content)
    
    const res = await createDiscussion(submitData)
    if (res.code === 200) {
      toast.success('发布成功！')
      emit('submit', res.data)
    }
  } catch (error) {
    console.error('发布失败:', error)
    toast.error(error.message || '发布失败，请重试')
  } finally {
    submitting.value = false
  }
}

function handleClose() {
  emit('close')
}

function handleInsertFormula(latex) {
  // 在光标位置插入公式
  const textarea = contentTextarea.value
  if (!textarea) return
  
  const start = textarea.selectionStart
  const end = textarea.selectionEnd
  const before = formData.value.content.substring(0, start)
  const after = formData.value.content.substring(end)
  
  // 用特殊标记包裹公式
  const formulaText = ` $$${latex}$$ `
  formData.value.content = before + formulaText + after
  
  // 关闭编辑器
  showMathEditor.value = false
  
  // 聚焦回textarea
  setTimeout(() => {
    const newPos = start + formulaText.length
    textarea.setSelectionRange(newPos, newPos)
    textarea.focus()
  }, 100)
}

function triggerImageUpload() {
  imageInput.value?.click()
}

async function handleImageUpload(event) {
  const files = Array.from(event.target.files)
  if (files.length === 0) return
  
  // 验证图片
  const validFiles = []
  for (const file of files) {
    // 检查文件类型
    if (!file.type.startsWith('image/')) {
      toast.warning(`${file.name} 不是图片文件`)
      continue
    }
    
    // 检查文件大小（最大5MB）
    if (file.size > 5 * 1024 * 1024) {
      toast.warning(`${file.name} 文件过大，请选择小于5MB的图片`)
      continue
    }
    
    validFiles.push(file)
  }
  
  if (validFiles.length === 0) {
    event.target.value = ''
    return
  }
  
  uploading.value = true
  
  try {
    for (const file of validFiles) {
      // 上传到OSS服务器
      const formDataObj = new FormData()
      formDataObj.append('file', file)
      
      console.log('正在上传图片:', file.name)
      const res = await uploadImage(formDataObj)
      
      if (res.code === 200) {
        console.log('图片上传成功，URL:', res.data.url)
        uploadedImages.value.push({
          name: file.name,
          url: res.data.url  // 使用OSS返回的URL
        })
      } else {
        throw new Error(res.message || '上传失败')
      }
    }
    
    if (validFiles.length > 0) {
      toast.success(`成功上传 ${validFiles.length} 张图片！`)
    }
  } catch (error) {
    console.error('图片上传失败:', error)
    toast.error(error.message || '图片上传失败，请重试')
  } finally {
    uploading.value = false
    event.target.value = ''
  }
}

function removeImage(index) {
  uploadedImages.value.splice(index, 1)
}
</script>

<style lang="scss" scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: 20px;
}

.modal-container {
  background: white;
  border-radius: 16px;
  width: 100%;
  max-width: 700px;
  max-height: 90vh;
  display: flex;
  flex-direction: column;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
}

.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24px 32px;
  border-bottom: 1px solid #eee;
  
  h2 {
    font-size: 22px;
    font-weight: bold;
    color: #333;
    margin: 0;
  }
  
  .close-btn {
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: none;
    border: none;
    border-radius: 50%;
    color: #999;
    cursor: pointer;
    transition: all 0.2s;
    
    &:hover {
      background: #f5f5f5;
      color: #333;
    }
  }
}

.modal-body {
  flex: 1;
  overflow-y: auto;
  padding: 24px 32px;
  
  .form-group {
    margin-bottom: 24px;
    position: relative;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
  
  .form-label {
    display: block;
    font-size: 14px;
    font-weight: 600;
    color: #333;
    margin-bottom: 8px;
    
    .required {
      color: #ff4757;
      margin-left: 4px;
    }
  }
  
  .form-input {
    width: 100%;
    padding: 12px 16px;
    border: 1.5px solid #e0e0e0;
    border-radius: 8px;
    font-size: 15px;
    transition: all 0.2s;
    
    &:focus {
      outline: none;
      border-color: #667eea;
      box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
    }
    
    &::placeholder {
      color: #bbb;
    }
  }
  
  .editor-wrapper {
    border: 1.5px solid #e0e0e0;
    border-radius: 8px;
    overflow: hidden;
    transition: all 0.2s;
    
    &:focus-within {
      border-color: #667eea;
      box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
    }
  }
  
  .editor-toolbar {
    display: flex;
    gap: 8px;
    padding: 10px 12px;
    background: #f9fafb;
    border-bottom: 1px solid #e5e7eb;
    
    .toolbar-btn {
      display: flex;
      align-items: center;
      gap: 6px;
      padding: 6px 12px;
      background: white;
      color: #666;
      border: 1px solid #e0e0e0;
      border-radius: 6px;
      font-size: 13px;
      cursor: pointer;
      transition: all 0.2s;
      
      &:disabled {
        opacity: 0.6;
        cursor: not-allowed;
        
        &:hover {
          background: white;
          color: #666;
          border-color: #e0e0e0;
          transform: none;
          box-shadow: none;
        }
      }
      
      &:not(:disabled):hover {
        background: #667eea;
        color: white;
        border-color: #667eea;
        transform: translateY(-1px);
        box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
      }
      
      svg {
        display: block;
        
        &.spinning {
          animation: spin 1s linear infinite;
        }
      }
    }
  }
  
  @keyframes spin {
    from {
      transform: rotate(0deg);
    }
    to {
      transform: rotate(360deg);
    }
  }
  
  .form-textarea {
    width: 100%;
    padding: 12px 16px;
    border: none;
    font-size: 15px;
    font-family: inherit;
    resize: vertical;
    
    &:focus {
      outline: none;
    }
    
    &::placeholder {
      color: #bbb;
    }
  }
  
  .editor-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 12px;
    background: #f9fafb;
    border-top: 1px solid #e5e7eb;
    gap: 16px;
    
    .footer-left {
      flex: 1;
      min-width: 0;
    }
    
    .char-count {
      font-size: 12px;
      color: #999;
      white-space: nowrap;
    }
  }
  
  .image-previews {
    .images-label {
      font-size: 13px;
      color: #666;
      font-weight: 500;
      margin-bottom: 8px;
      display: inline-block;
    }
    
    .image-list {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
      margin-top: 8px;
    }
    
    .image-preview-item {
      position: relative;
      width: 80px;
      height: 80px;
      border-radius: 6px;
      overflow: hidden;
      border: 2px solid #e5e7eb;
      background: white;
      transition: all 0.2s;
      
      &:hover {
        border-color: #667eea;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(102, 126, 234, 0.2);
      }
      
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
      
      .remove-image {
        position: absolute;
        top: 3px;
        right: 3px;
        width: 20px;
        height: 20px;
        display: flex;
        align-items: center;
        justify-content: center;
        background: rgba(0, 0, 0, 0.7);
        color: white;
        border: none;
        border-radius: 50%;
        cursor: pointer;
        opacity: 0;
        transition: all 0.2s;
        
        &:hover {
          background: #ff4757;
          transform: scale(1.1);
        }
      }
      
      &:hover .remove-image {
        opacity: 1;
      }
    }
  }
  
  .tags-input {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    padding: 8px;
    border: 1.5px solid #e0e0e0;
    border-radius: 8px;
    min-height: 48px;
    transition: all 0.2s;
    
    &:focus-within {
      border-color: #667eea;
      box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
    }
    
    .tag-item {
      display: flex;
      align-items: center;
      gap: 4px;
      padding: 4px 12px;
      background: #ede7f6;
      color: #667eea;
      border-radius: 16px;
      font-size: 14px;
      
      .tag-remove {
        background: none;
        border: none;
        color: #667eea;
        font-size: 20px;
        line-height: 1;
        cursor: pointer;
        padding: 0;
        margin-left: 4px;
        
        &:hover {
          color: #ff4757;
        }
      }
    }
    
    .tag-input {
      flex: 1;
      min-width: 120px;
      border: none;
      outline: none;
      font-size: 14px;
      
      &::placeholder {
        color: #bbb;
      }
    }
  }
  
  .tag-suggestions {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin-top: 12px;
    
    .suggested-tag {
      padding: 4px 12px;
      background: #f5f7fa;
      color: #666;
      border-radius: 16px;
      font-size: 13px;
      cursor: pointer;
      transition: all 0.2s;
      
      &:hover {
        background: #ede7f6;
        color: #667eea;
      }
    }
  }
}

.modal-footer {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px 32px;
  border-top: 1px solid #eee;
  
  .btn {
    padding: 10px 24px;
    border: none;
    border-radius: 8px;
    font-size: 15px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;
    
    &.btn-cancel {
      background: #f5f7fa;
      color: #666;
      
      &:hover {
        background: #e8ecf1;
      }
    }
    
    &.btn-submit {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      
      &:hover:not(:disabled) {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
      }
      
      &:disabled {
        opacity: 0.5;
        cursor: not-allowed;
      }
    }
  }
}

@media (max-width: 768px) {
  .modal-container {
    max-width: 100%;
    max-height: 100vh;
    border-radius: 0;
  }
  
  .modal-header, .modal-body, .modal-footer {
    padding-left: 20px;
    padding-right: 20px;
  }
}
</style>

